﻿namespace EyeOpen.Data.Nhibernate
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Reflection;
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;

    public class FluentConfigurationHelper
    {
        public FluentConfiguration CreateFluentConfiguration(string connectionStringKey, IEnumerable<Assembly> mappingAssemblyCollection)
        {
            var connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringKey];
            
            if (connectionStringSettings == null)
            {
                string message = string.Format("Must define \"{0}\" connection string key in the configuration file.", connectionStringKey);
                throw new ConfigurationErrorsException(message);
            }

            if (connectionStringSettings.ProviderName != "System.Data.SqlClient")
            {
                throw new NotSupportedException("Provider \"{0}\" is not supported.");
            }

            var connectionString = connectionStringSettings.ConnectionString;

            var sqlDatabase =
                MsSqlConfiguration
                    .MsSql2005
                    .ConnectionString(x => x.Is(connectionString))
                    .UseReflectionOptimizer();

            var fluentConfiguration =
                Fluently.Configure()
                    .Database(sqlDatabase);

            foreach (var mappingAssembly in mappingAssemblyCollection)
            {
                var assembly = mappingAssembly;

                fluentConfiguration.Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
            }

            return fluentConfiguration;
        }
    }
}